package com.jfee.dds.interceptors;

import com.jfee.dds.config.TenantPropertiesConfig;
import com.jfee.dds.datasource.DBIdentifier;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口服务拦截器
 */
@Slf4j
@Component
public class ServiceInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TenantPropertiesConfig tenantConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = tenantConfig.getHeader();
        String tenantId = request.getHeader(header);
        if (StringUtils.isBlank(tenantId)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "参数错误");
            return false;
        }
        DBIdentifier.setTenantId(tenantId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
